import sys
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from PySide6.QtGui import *


class ChessPiece(QGraphicsItem):
    def __init__(self, piece_type, color, pos):
        super().__init__()
        self.piece_type = piece_type.upper()
        self.color = color  # 'red' 或 'black'
        self.pos = pos
        self.setPos((pos[0] - 1) * 55 + 30, (9 - pos[1]) * 55 + 30)
        self.selected = False

    def boundingRect(self):
        return QRectF(-20, -20, 40, 40)

    def paint(self, painter, option, widget):
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(QBrush(QColor(255, 228, 181) if self.color == 'red' else QColor(139, 69, 19)))
        painter.setPen(QPen(Qt.black, 1))
        painter.drawEllipse(-20, -20, 40, 40)

        font = QFont("SimSun", 18)
        painter.setFont(font)
        painter.setPen(QColor(255, 255, 255) if self.color == 'black' else QColor(0, 0, 0))
        text_map = {
            'K': '将', 'A': '士', 'B': '象', 'R': '车',
            'N': '马', 'C': '炮', 'P': '兵'
        }
        painter.drawText(-15, 10, text_map[self.piece_type])


class ChessBoard(QGraphicsView):
    def __init__(self):
        super().__init__()
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        self.setSceneRect(0, 0, 580, 640)
        self.setFixedSize(580, 640)
        self.pieces = {}
        self.selected_piece = None
        self.current_player = 'red'  # 当前行棋方
        self.game_over = False
        self.init_board()
        self.draw_board()

    def init_board(self):
        self.load_fen("rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r - - 0 1")

    def draw_board(self):
        #...（保持原有棋盘绘制代码不变）...
        self.scene.addRect(0, 0, 580, 640, brush=QBrush(QColor(245, 222, 179)))

    def load_fen(self, fen):
        self.pieces.clear()
        parts = fen.split()
        rows = parts[0].split('/')

        piece_map = {
            'r': ('R', 'black'), 'n': ('N', 'black'), 'b': ('B', 'black'),
            'a': ('A', 'black'), 'k': ('K', 'black'), 'c': ('C', 'black'),
            'p': ('P', 'black'),
            'R': ('R', 'red'), 'N': ('N', 'red'), 'B': ('B', 'red'),
            'A': ('A', 'red'), 'K': ('K', 'red'), 'C': ('C', 'red'),
            'P': ('P', 'red')
        }

        for y, row in enumerate(rows):
            x = 0
            for c in row:
                if c.isdigit():
                    x += int(c)
                else:
                    piece_type, color = piece_map[c]
                    pos = (x + 1, 10 - y)
                    self.pieces[pos] = ChessPiece(piece_type, color, pos)
                    self.scene.addItem(self.pieces[pos])
                    x += 1

        # 解析其他FEN参数
        self.current_player = 'red' if parts[1] == 'r' else 'black'

    def is_valid_move(self, start, end):
        # 走法验证核心逻辑
        piece = self.pieces.get(start)
        target = self.pieces.get(end)

        if not piece or piece.color != self.current_player:
            return False

        # 通用规则检查
        dx = end[0] - start[0]
        dy = end[1] - start[1]

        # 各棋子走法规则
        if piece.piece_type == 'R':  # 车
            return self.validate_rook(start, end)
        elif piece.piece_type == 'N':  # 马
            return self.validate_knight(start, end)
        elif piece.piece_type == 'C':  # 炮
            return self.validate_cannon(start, end)
        # ...（其他棋子规则实现）...

        return False

    def validate_rook(self, start, end):
        # 车：直线移动且路径无障碍
        if start[0] != end[0] and start[1] != end[1]:
            return False

        step = 1 if end[0] > start[0] or end[1] > start[1] else -1
        if start[0] == end[0]:  # 垂直移动
            for y in range(start[1] + step, end[1], step):
                if (start[0], y) in self.pieces:
                    return False
        else:  # 水平移动
            for x in range(start[0] + step, end[0], step):
                if (x, start[1]) in self.pieces:
                    return False
        return True

    def mousePressEvent(self, event):
        if self.game_over:
            return

        pos = self.mapToScene(event.pos())
        x = round((pos.x() - 30) / 55) + 1
        y = 10 - round((pos.y() - 30) / 55)

        if event.button() == Qt.LeftButton:
            if (x, y) in self.pieces:
                if self.pieces[(x, y)].color == self.current_player:
                    self.selected_piece = self.pieces[(x, y)]
            elif self.selected_piece:
                if self.is_valid_move(self.selected_piece.pos, (x, y)):
                    self.move_piece(self.selected_piece.pos, (x, y))
                    self.current_player = 'black' if self.current_player == 'red' else 'red'
                    self.check_game_over()
                self.selected_piece = None

    def move_piece(self, start, end):
        # 执行移动
        piece = self.pieces[start]
        if end in self.pieces:  # 吃子
            self.scene.removeItem(self.pieces[end])
            del self.pieces[end]
        del self.pieces[start]
        piece.pos = end
        self.pieces[end] = piece
        piece.set_pos((end[0] - 1) * 55 + 30, (9 - end[1]) * 55 + 30)

    def check_game_over(self):
        # 胜负判断（检查双方将/帅是否存在）
        has_red_king = any(p.piece_type == 'K' and p.color == 'red' for p in self.pieces.values())
        has_black_king = any(p.piece_type == 'K' and p.color == 'black' for p in self.pieces.values())

        if not has_red_king:
            self.show_message("黑方胜利！")
            self.game_over = True
        elif not has_black_king:
            self.show_message("红方胜利！")
            self.game_over = True

    def show_message(self, text):
        msg = QMessageBox()
        msg.setText(text)
        msg.exec()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("中国象棋")
        self.board = ChessBoard()
        self.setCentralWidget(self.board)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())